package tasks;

import java.util.concurrent.LinkedBlockingQueue;

import core.Piece;
import core.PieceQueue;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.RandomAccessFile;

public class ProcessPieceQueue implements Runnable {

    private LinkedBlockingQueue<Piece> pieceQueue;

    public ProcessPieceQueue() {
        this.pieceQueue = PieceQueue.getPieceQueue();
    }

    @Override
    public void run() {
        Piece piece = null;

        do {
            try {
                piece = this.pieceQueue.take();
                RandomAccessFile raf = new RandomAccessFile(piece.getPath(), "rw");
                raf.seek(piece.getIndex()*piece.getStandardLength());                
                raf.write(piece.getData());
                raf.close();
            } catch (InterruptedException e) {
                System.out.println("ProcessPieceQueue|InterruptedException: " + e);
            } catch (Exception e) {
                System.out.println("ProcessPieceQueue|Exception: "+e);
            }
        } while (true);

    }
}
